﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors; 
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using System.Linq;
using DAL;
using BLL;
using DTO;
using DevExpress.LookAndFeel;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;

namespace CRM.GUI.QLCuocGoi
{
    public partial class frmNewCall : DevExpress.XtraEditors.XtraForm
    {
        //=========================================
        IBDetailEntity _ib = new IBDetailEntity();
        CustomerEntity _customer;
        IBDetailTempFunc _ibFunc = new IBDetailTempFunc();
        string phone;


        public frmNewCall(string number)
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            UserLookAndFeel.Default.SetSkinStyle("Office 2007 Blue");

            phone = number;
            InitializeComponent();
            IntialConfig();
            InitGrid();
            IntialLoad();
            LoadCus(number);
        }

        private void IntialConfig()
        {
            grdviewcallHistory.BestFitColumns();
            grdviewcallHistory.OptionsView.ColumnAutoWidth = false;
            grdviewcallHistory.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            grdviewcallHistory.HorzScrollVisibility = ScrollVisibility.Always;

            grdViewNew.BestFitColumns();
            grdViewNew.OptionsView.ColumnAutoWidth = false;
            grdViewNew.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            grdViewNew.HorzScrollVisibility = ScrollVisibility.Always;

            colRecord.UnboundType = DevExpress.Data.UnboundColumnType.String;
            colCallDuration.UnboundType = DevExpress.Data.UnboundColumnType.String;
            grdViewRecord.CustomUnboundColumnData += colRecord_CustomUnboundColumnData;
            grdViewRecord.CustomUnboundColumnData += colCallDuration_CustomUnboundColumnData;
        }

        private void InitGrid()
        {
            grdcallNew.ForceInitialize();

            colrepBrandName.DataSource = SharedData.BrandList;
            colrepBrandName.DisplayMember = "Brand_Code";
            colrepBrandName.ValueMember = "Brand_ID";

            GridColumn bColumn = colrepBrandName.View.Columns.AddField("Brand_Code");
            GridColumn cColumn = colrepBrandName.View.Columns.AddField("BrandName");

            bColumn.Visible = true;
            cColumn.Visible = true;

            bColumn = gridView1.Columns["Brand_Code"];
            bColumn.Caption = "Mã sữa";
            cColumn = gridView1.Columns["BrandName"];
            cColumn.Caption = "Tên sữa";

        }
       
        private void IntialLoad()
        {

            cmbBranIDLookUp.DataSource = SharedData.BrandList;
            cmbBranIDLookUp.DisplayMember = "BrandName";
            cmbBranIDLookUp.ValueMember = "Brand_ID";

            cmbWard.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 4).ToList();
            cmbWard.DisplayMember = "RegionName";
            cmbWard.ValueMember = "Region_Code";

            cmbDistrict.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 3).ToList();
            cmbDistrict.DisplayMember = "RegionName";
            cmbDistrict.ValueMember = "Region_Code";

            cmbProvince.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 2).ToList();
            cmbProvince.DisplayMember = "RegionName";
            cmbProvince.ValueMember = "Region_Code";

            cmbCurrentBrand.DataSource = SharedData.BrandList.ToList();
            cmbCurrentBrand.DisplayMember = "Brand_Code";
            cmbCurrentBrand.ValueMember = "Brand_ID";

            cmbPreviousBrand.DataSource = SharedData.BrandList.ToList();
            cmbPreviousBrand.DisplayMember = "Brand_Code";
            cmbPreviousBrand.ValueMember = "Brand_ID";            
        }


        private DataTable CreateDataTable()
        {
            DataTable _table = new  DataTable();
            _table.Columns.Add("SourceReciving", typeof(string));
            _table.Columns.Add("Customer_ID", typeof(int));
            _table.Columns.Add("NXS", typeof(DateTime));
            _table.Columns.Add("HSD", typeof(DateTime));
            _table.Columns.Add("BrandNameID", typeof(int));
            _table.Columns.Add("ReasonComplain", typeof(string));
            _table.Columns.Add("Status", typeof(string));
            _table.Columns.Add("CRMResponse", typeof(string));
            _table.Columns.Add("SupplyResponse", typeof(string));
            _table.Columns.Add("FactoryResponse", typeof(string));
             _table.Columns.Add("ProductExchange", typeof(string));
            _table.Columns.Add("GiftProduct", typeof(string));
            _table.Columns.Add("DatetoFeedBack", typeof(DateTime));

            return _table;
        }

        private void LoadCus(string phonenumber)
        {
            _customer = _ibFunc.LoadCustomerByPhone(phonenumber);
            if (_customer != null)
            {

                txtFirstName.Text = _customer.FirstName;
                txtLastName.Text = _customer.LastName;
                txtCellPhone.Text = _customer.CellPhoneNumber;
                
                txtHomePhone.Text = _customer.HomePhoneNumber;
                txtOfficePhone.Text = _customer.OfficePhoneNumber;
                txtNote.Text = _customer.Note;
                txtIDNumber.Text = _customer.IDNumber;

                txtHomeNumber.Text = _customer.HomeNumber;
                txtStreet.Text = _customer.Street;
                txtSubStreet.Text = _customer.SubStreet;
                dtpEDD.EditValue = _customer.EDD;
                dtpDoBMom.EditValue = _customer.DateOfBirth;

                if (_customer.Province_Code != null)
                {
                    cmbProvince.SelectedValue = _customer.Province_Code;
                }
                if (_customer.District_Code != null)
                {
                    cmbDistrict.SelectedValue = _customer.District_Code;
                }
                if (_customer.Ward_Code != null)
                {
                    cmbWard.SelectedValue = _customer.Ward_Code;
                }

                var data = _ibFunc.LoadIBDetailByPhone(phone);
                if (data != null)
                {
                    if (data.Count > 1)
                    {
                        grdcallHistory.DataSource = data[0];
                        grdRecord.DataSource = data[1];
                    }
                    else
                    {
                        grdcallHistory.DataSource = data[0];
                    }
                }
                grdcallHistory.Refresh();
                grdviewcallHistory.BestFitColumns();
                grdViewRecord.BestFitColumns();

                grdcallNew.DataSource = CreateDataTable();
                grdViewNew_addRow();
                grdcallNew.Refresh();                
            }
            else
            {
                _customer = new CustomerEntity();
                txtCellPhone.Text = phone;
                grdcallNew.DataSource = CreateDataTable();
                grdViewNew_addRow();
                grdcallNew.Refresh();
            }
        }


        private void grdViewNew_addRow()
        {         
            grdViewNew.AddNewRow();

            int bottomRow = grdViewNew.RowCount - 1;
            grdViewNew.SetRowCellValue(bottomRow, clnSourceReciving, "");
            grdViewNew.SetRowCellValue(bottomRow, clnNSX, "");
            grdViewNew.SetRowCellValue(bottomRow, clnHSD, "");
            grdViewNew.SetRowCellValue(bottomRow, clnBrandNameID, "");
            grdViewNew.SetRowCellValue(bottomRow, clnReasonComplain, "");
            grdViewNew.SetRowCellValue(bottomRow, clnStatus, "");
            grdViewNew.SetRowCellValue(bottomRow, clnCRMResponse, "");
            grdViewNew.SetRowCellValue(bottomRow, clnSupplyResponse, "");
            grdViewNew.SetRowCellValue(bottomRow, clnFactoryResponse, "");
            grdViewNew.SetRowCellValue(bottomRow, clnProductExchange, "");
            grdViewNew.SetRowCellValue(bottomRow, clnGiftProduct, "");
            grdViewNew.SetRowCellValue(bottomRow, clnDatetoFeedBack, "");
            grdcallNew.Refresh();     
            
        }


        private void btnAdd_Click(object sender, EventArgs e)
        {
            int bottomRow = grdViewNew.RowCount - 1;

            if (txtFirstName.Text.Equals("") || txtLastName.Text.Equals(""))
            {
                MessageBox.Show("Vui lòng nhập Họ & Tên", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            

            if (grdViewNew.GetRowCellValue(bottomRow, clnBrandNameID) == null)
            {
                MessageBox.Show("Vui lòng nhập Tên sản phẩm", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                _ib.BrandNameID = int.Parse(grdViewNew.GetRowCellValue(bottomRow, clnBrandNameID).ToString());
            }


            if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(bottomRow, clnNSX).ToString()))
            { _ib.NSX = null; }
            else
            { 
                _ib.NSX = DateTime.Parse(grdViewNew.GetRowCellValue(bottomRow, clnNSX).ToString()); 
            }


            if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(bottomRow, clnHSD).ToString()))
            { _ib.HSD = null; }
            else
            { _ib.HSD = DateTime.Parse(grdViewNew.GetRowCellValue(bottomRow, clnHSD).ToString()); }


            if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(bottomRow, clnDatetoFeedBack).ToString()))
            { _ib.DatetoFeedBack = null; }
            else
            { _ib.DatetoFeedBack = DateTime.Parse(grdViewNew.GetRowCellValue(bottomRow, clnDatetoFeedBack).ToString()); }



            _ib.DateOfComplain = DateTime.Today;
            _ib.SourceReciving = grdViewNew.GetRowCellValue(bottomRow, clnSourceReciving).ToString();
            _ib.ReasonComplain = grdViewNew.GetRowCellValue(bottomRow, clnReasonComplain).ToString();
            _ib.Status = grdViewNew.GetRowCellValue(bottomRow, clnStatus).ToString();
            _ib.CRMResponse = grdViewNew.GetRowCellValue(bottomRow, clnCRMResponse).ToString();
            _ib.SupplyResponse = grdViewNew.GetRowCellValue(bottomRow, clnSupplyResponse).ToString();
            _ib.FactoryResponse = grdViewNew.GetRowCellValue(bottomRow, clnFactoryResponse).ToString();
            _ib.ProductExchange = grdViewNew.GetRowCellValue(bottomRow, clnProductExchange).ToString();
            _ib.GiftProduct = grdViewNew.GetRowCellValue(bottomRow, clnGiftProduct).ToString();

            
            _customer.FirstName = txtFirstName.Text.ToString();
            _customer.LastName = txtLastName.Text.ToString();
            _customer.CellPhoneNumber = txtCellPhone.Text.ToString();

            _customer.HomePhoneNumber = txtHomePhone.Text.ToString();
            _customer.OfficePhoneNumber = txtOfficePhone.Text.ToString();
            _customer.Note = txtNote.Text.ToString();
            _customer.IDNumber = txtIDNumber.Text.ToString();

            _customer.HomeNumber = txtHomeNumber.Text.ToString();
            _customer.Street = txtStreet.Text.ToString();
            _customer.SubStreet = txtSubStreet.Text.ToString();

            if (dtpEDD.EditValue != null)
            {
                if (string.IsNullOrEmpty(dtpEDD.EditValue.ToString()))
                {
                    _customer.EDD = null;
                }
                else
                {
                    _customer.EDD = DateTime.Parse(dtpEDD.EditValue.ToString());
                }
            }


            if (dtpDoBMom.EditValue != null)
            {
                if (string.IsNullOrEmpty(dtpDoBMom.EditValue.ToString()))
                {
                    _customer.DateOfBirth = null;
                }
                else
                {
                    _customer.DateOfBirth = DateTime.Parse(dtpDoBMom.EditValue.ToString());
                }
            }

            if (cmbProvince.SelectedValue != null)
            {
                _customer.Province_Code = int.Parse(cmbProvince.SelectedValue.ToString());
            }

            if (cmbDistrict.SelectedValue != null)
            {
                _customer.District_Code = int.Parse(cmbDistrict.SelectedValue.ToString());
            }

            if (cmbWard.SelectedValue != null)
            {
                _customer.Ward_Code = int.Parse(cmbWard.SelectedValue.ToString());
            }

            if (cmbCurrentBrand.SelectedValue != null)
            {
                _customer.CurrentBrandName = int.Parse(cmbCurrentBrand.SelectedValue.ToString());
            }

            if (cmbPreviousBrand.SelectedValue != null)
            {
                _customer.PreviousBrandName = int.Parse(cmbPreviousBrand.SelectedValue.ToString());
            }
            
            _ibFunc.AddIBDetailTemp(_customer, _ib);

            grdViewNew.DeleteRow(bottomRow);

            grdcallNew.Refresh();
            var data = _ibFunc.LoadIBDetailByPhone(phone);
            if (data != null)
            {
                if (data.Count > 1)
                {
                    grdcallHistory.DataSource = data[0];
                    grdRecord.DataSource = data[1];
                }
                else
                {
                    grdcallHistory.DataSource = data[0];
                }
            }
            grdcallHistory.Refresh();
            grdViewRecord.BestFitColumns();
            grdviewcallHistory.MoveLast();
            grdViewRecord.MoveLast();
            grdviewcallHistory.BestFitColumns();
        }

        private void colRecord_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
            {                
                var data = e.Row as RecordEntity;
                if (e.Column.Name == "colRecord" && e.Column.FieldName == "Record")
                {
                    e.Value = "Tải xuống";
                }                
            }            
        }

        private void colCallDuration_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
            {
                var data = e.Row as RecordEntity;
                if (e.Column.Name == "colCallDuration")
                {
                    e.Value = HelperClass.GetDuration(data.Duration);
                }
            }
        }

        private void frmNewCall_FormClosing(object sender, FormClosingEventArgs e)
        {
            //CallMonitor c = new CallMonitor();
            //c.ReadyToCall();
            //c.CloseThread();
        }
        private void cmbDistrict_SelectionChangeCommitted(object sender, EventArgs e)
        {
                // Tự động load phường xã theo quận huyện
            int districtcode = (int)cmbDistrict.SelectedValue;
            cmbWard.DataSource = SharedData.RegionList.Where(a => a.Parent_Code == districtcode).ToList();
            cmbWard.DisplayMember = "RegionName";
            cmbWard.ValueMember = "Region_Code";
        }

        private void cmbProvince_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // Tự động load quận huyện theo tỉnh thành
            int provincecode = (int)cmbProvince.SelectedValue;
            cmbDistrict.DataSource = SharedData.RegionList.Where(a => a.Parent_Code == provincecode).ToList();
            cmbDistrict.DisplayMember = "RegionName";
            cmbDistrict.ValueMember = "Region_Code";
            // Tự động load phường xã theo quận huyện
            int districtcode = (int)cmbDistrict.SelectedValue;
            cmbWard.DataSource = SharedData.RegionList.Where(a => a.Parent_Code == districtcode).ToList();
            cmbWard.DisplayMember = "RegionName";
            cmbWard.ValueMember = "Region_Code";
        }

        private void grdViewRecord_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.Name == "colRecord")
            {
                var data = (RecordEntity)grdViewRecord.GetRow(e.RowHandle);
                if (!string.IsNullOrEmpty(data.RecordLink))
                {
                    CallManagement cm = new CallManagement();
                    cm.DownloadFileRecord(data.RecordLink);
                    MessageBox.Show("Đã download xong!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.None);
                }
            }
        }
          
    }
}